package com.itsol.smartphone.dao;

import java.util.List;

import org.hibernate.SessionFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Repository;
import org.springframework.transaction.annotation.Transactional;

import com.itsol.smartphone.entity.Smartphone;
import com.itsol.smartphone.exception.SmartphoneNotFoundException;

@Repository
public class SmartphoneDAOImpl implements SmartphoneDAO {

	@Autowired
    private SessionFactory sessionFactory;
	
	@Transactional
	public Smartphone create(Smartphone sp) {
		sessionFactory.getCurrentSession().save(sp);
		return sp;
	}

	@Transactional
	public Smartphone get(Integer id) {
		Smartphone sp = (Smartphone) sessionFactory.openSession().load(
				Smartphone.class, id);
		return sp;
	}

	@SuppressWarnings("unchecked")
	@Transactional
	public List<Smartphone> getAll() {
		return sessionFactory.getCurrentSession().createQuery("from Smartphone")
                .list();
	}

	@Transactional
	public Smartphone update(Smartphone sp) throws SmartphoneNotFoundException {
		Smartphone sPhoneToUpdate = get(sp.getId());
		if (sPhoneToUpdate == null) {
			throw new SmartphoneNotFoundException(sp.getId().toString());
		}
		
		sPhoneToUpdate.update(sp);
		sessionFactory.getCurrentSession().merge(sPhoneToUpdate);
		
		return sPhoneToUpdate;
	}

	@Transactional
	public Smartphone delete(Integer id) throws SmartphoneNotFoundException {
		Smartphone sPhone = get(id);
		if (sPhone == null) {
			throw new SmartphoneNotFoundException(id.toString());
		}
		
		sessionFactory.getCurrentSession().delete(sPhone);
		return sPhone;
	}

}
